package com.wl.web.controller;

import com.wl.web.domain.User;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import javax.servlet.http.HttpSession;

/**
 * 用戶登录控制器
 *
 * @author wl
 */
@Controller
public class LoginController {
  @RequestMapping(method = RequestMethod.GET, value = "/login")
  public String getPage(Model model) {
    User user = new User();
    model.addAttribute("user", user);
    return "login";
  }

  @RequestMapping(method = RequestMethod.POST, value = "/login")
  public String login(@Validated User user, BindingResult bindingResult, HttpSession httpSession) {
    if (bindingResult.hasErrors()) {
      return "login";
    } else {
      httpSession.setAttribute("username", user.getUsername());
      return "redirect:/index";
    }
  }
}
